/**
 * 数据同步任务进度演示组件
 * 用于测试和演示多任务并发监控功能
 */

import React, { useState, useCallback } from 'react';
import { Card, Button, Space, Typography, Divider, Tag, Progress, Row, Col } from 'antd';
import { PlayCircleOutlined, PauseCircleOutlined, StopOutlined, ReloadOutlined } from '@ant-design/icons';
import { useSyncTaskProgress } from '../hooks/useSyncTaskProgress';
import { globalSyncTaskManager } from '../utils/globalSyncTaskManager';

const { Title, Text } = Typography;

interface DemoTask {
  id: string;
  name: string;
  sourceType: string;
  targetType: string;
  notificationId?: string;
  isRunning: boolean;
  progress: number;
  status: 'idle' | 'running' | 'completed' | 'failed' | 'paused';
}

const SyncTaskProgressDemo: React.FC = () => {
  const syncProgressHook = useSyncTaskProgress();
  const [demoTasks, setDemoTasks] = useState<DemoTask[]>([
    {
      id: 'demo-1',
      name: '用户数据同步',
      sourceType: 'MySQL',
      targetType: 'Doris',
      isRunning: false,
      progress: 0,
      status: 'idle'
    },
    {
      id: 'demo-2',
      name: '订单数据同步',
      sourceType: 'PostgreSQL',
      targetType: 'CSV',
      isRunning: false,
      progress: 0,
      status: 'idle'
    },
    {
      id: 'demo-3',
      name: '产品数据同步',
      sourceType: 'Oracle',
      targetType: 'Kafka',
      isRunning: false,
      progress: 0,
      status: 'idle'
    },
    {
      id: 'demo-4',
      name: '日志数据同步',
      sourceType: 'SQL Server',
      targetType: 'Doris',
      isRunning: false,
      progress: 0,
      status: 'idle'
    }
  ]);

  // 启动演示任务
  const startDemoTask = useCallback((taskId: string) => {
    const task = demoTasks.find(t => t.id === taskId);
    if (!task || task.isRunning) return;

    // 启动Dynamic Island通知
    const notificationId = syncProgressHook.startSyncTask(
      task.name,
      task.sourceType,
      task.targetType
    );

    // 更新任务状态
    setDemoTasks(prev => prev.map(t => 
      t.id === taskId 
        ? { ...t, notificationId, isRunning: true, status: 'running' as const, progress: 0 }
        : t
    ));

    // 模拟进度更新
    let progress = 0;
    const interval = setInterval(() => {
      progress += Math.random() * 15 + 5; // 每次增加5-20%
      
      if (progress >= 100) {
        progress = 100;
        clearInterval(interval);
        
        // 完成任务
        const success = Math.random() > 0.2; // 80%成功率
        syncProgressHook.completeSyncTask(
          notificationId,
          success,
          success 
            ? `${task.name}同步完成：处理 ${Math.floor(Math.random() * 10000 + 1000)} 条记录`
            : `${task.name}同步失败：网络连接超时`,
          {
            processedRecords: Math.floor(Math.random() * 10000 + 1000),
            successRecords: Math.floor(Math.random() * 9000 + 900),
            failedRecords: Math.floor(Math.random() * 100),
            duration: Math.floor(Math.random() * 300 + 60)
          }
        );

        // 更新任务状态
        setDemoTasks(prev => prev.map(t => 
          t.id === taskId 
            ? { 
                ...t, 
                isRunning: false, 
                status: success ? 'completed' as const : 'failed' as const,
                progress: 100 
              }
            : t
        ));
        return;
      }

      // 更新进度
      const stages = [
        '连接数据源',
        '读取源数据', 
        '数据转换处理',
        '写入目标数据',
        '完成数据验证'
      ];
      const stageIndex = Math.floor(progress / 20);
      const currentStage = stages[Math.min(stageIndex, stages.length - 1)];

      syncProgressHook.updateSyncProgress(
        notificationId,
        progress,
        currentStage,
        Math.floor(progress * 100),
        10000,
        {
          successRecords: Math.floor(progress * 90),
          failedRecords: Math.floor(progress * 2),
          currentBatch: Math.floor(progress / 10) + 1,
          totalBatches: 10,
          estimatedTimeRemaining: Math.floor((100 - progress) * 2)
        }
      );

      // 更新本地进度显示
      setDemoTasks(prev => prev.map(t => 
        t.id === taskId ? { ...t, progress: Math.round(progress) } : t
      ));
    }, 1000 + Math.random() * 1000); // 1-2秒间隔

  }, [demoTasks, syncProgressHook]);

  // 暂停演示任务
  const pauseDemoTask = useCallback((taskId: string) => {
    const task = demoTasks.find(t => t.id === taskId);
    if (!task || !task.notificationId) return;

    syncProgressHook.pauseSyncTask(task.notificationId);
    setDemoTasks(prev => prev.map(t => 
      t.id === taskId ? { ...t, status: 'paused' as const } : t
    ));
  }, [demoTasks, syncProgressHook]);

  // 恢复演示任务
  const resumeDemoTask = useCallback((taskId: string) => {
    const task = demoTasks.find(t => t.id === taskId);
    if (!task || !task.notificationId) return;

    syncProgressHook.resumeSyncTask(task.notificationId);
    setDemoTasks(prev => prev.map(t => 
      t.id === taskId ? { ...t, status: 'running' as const } : t
    ));
  }, [demoTasks, syncProgressHook]);

  // 停止演示任务
  const stopDemoTask = useCallback((taskId: string) => {
    const task = demoTasks.find(t => t.id === taskId);
    if (!task || !task.notificationId) return;

    syncProgressHook.cancelSyncTask(task.notificationId, '用户手动停止');
    setDemoTasks(prev => prev.map(t => 
      t.id === taskId 
        ? { ...t, isRunning: false, status: 'idle' as const, progress: 0, notificationId: undefined }
        : t
    ));
  }, [demoTasks, syncProgressHook]);

  // 重置所有任务
  const resetAllTasks = useCallback(() => {
    demoTasks.forEach(task => {
      if (task.notificationId) {
        syncProgressHook.cancelSyncTask(task.notificationId, '重置演示');
      }
    });

    setDemoTasks(prev => prev.map(t => ({
      ...t,
      isRunning: false,
      status: 'idle' as const,
      progress: 0,
      notificationId: undefined
    })));
  }, [demoTasks, syncProgressHook]);

  // 启动所有任务
  const startAllTasks = useCallback(() => {
    demoTasks.forEach(task => {
      if (!task.isRunning) {
        setTimeout(() => startDemoTask(task.id), Math.random() * 2000); // 随机延迟启动
      }
    });
  }, [demoTasks, startDemoTask]);

  const getStatusColor = (status: DemoTask['status']) => {
    switch (status) {
      case 'running': return 'processing';
      case 'completed': return 'success';
      case 'failed': return 'error';
      case 'paused': return 'warning';
      default: return 'default';
    }
  };

  const getStatusText = (status: DemoTask['status']) => {
    switch (status) {
      case 'running': return '运行中';
      case 'completed': return '已完成';
      case 'failed': return '失败';
      case 'paused': return '已暂停';
      default: return '待启动';
    }
  };

  return (
    <Card title="数据同步任务进度演示" style={{ margin: '20px' }}>
      <div style={{ marginBottom: '20px' }}>
        <Title level={4}>多任务并发监控演示</Title>
        <Text type="secondary">
          此演示展示了DataPlexus数据同步任务与Dynamic Island通知系统的集成效果。
          启动任务后，您可以在页面右上角的Dynamic Island中看到实时进度更新。
        </Text>
      </div>

      <div style={{ marginBottom: '20px' }}>
        <Space>
          <Button 
            type="primary" 
            icon={<PlayCircleOutlined />}
            onClick={startAllTasks}
          >
            启动所有任务
          </Button>
          <Button 
            icon={<ReloadOutlined />}
            onClick={resetAllTasks}
          >
            重置所有任务
          </Button>
          <Text type="secondary">
            当前监控任务数: {globalSyncTaskManager.getMonitoringTaskCount()}
          </Text>
        </Space>
      </div>

      <Divider />

      <Row gutter={[16, 16]}>
        {demoTasks.map(task => (
          <Col xs={24} sm={12} lg={6} key={task.id}>
            <Card 
              size="small"
              title={
                <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>
                  <Text strong>{task.name}</Text>
                  <Tag color={getStatusColor(task.status)}>
                    {getStatusText(task.status)}
                  </Tag>
                </div>
              }
            >
              <div style={{ marginBottom: '12px' }}>
                <Text type="secondary">
                  {task.sourceType} → {task.targetType}
                </Text>
              </div>
              
              <Progress 
                percent={task.progress} 
                size="small"
                status={task.status === 'failed' ? 'exception' : 'normal'}
                style={{ marginBottom: '12px' }}
              />

              <Space size="small">
                {!task.isRunning ? (
                  <Button 
                    size="small"
                    type="primary"
                    icon={<PlayCircleOutlined />}
                    onClick={() => startDemoTask(task.id)}
                    disabled={task.status === 'completed'}
                  >
                    启动
                  </Button>
                ) : (
                  <>
                    {task.status === 'running' ? (
                      <Button 
                        size="small"
                        icon={<PauseCircleOutlined />}
                        onClick={() => pauseDemoTask(task.id)}
                      >
                        暂停
                      </Button>
                    ) : (
                      <Button 
                        size="small"
                        type="primary"
                        icon={<PlayCircleOutlined />}
                        onClick={() => resumeDemoTask(task.id)}
                      >
                        恢复
                      </Button>
                    )}
                    <Button 
                      size="small"
                      danger
                      icon={<StopOutlined />}
                      onClick={() => stopDemoTask(task.id)}
                    >
                      停止
                    </Button>
                  </>
                )}
              </Space>
            </Card>
          </Col>
        ))}
      </Row>
    </Card>
  );
};

export default SyncTaskProgressDemo;
